package com.hope.onlinestudy.activity.webview

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.support.annotation.RequiresApi
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.webkit.*
import com.hope.onlinestudy.R
import com.hope.onlinestudy.mvp.MVPBaseActivity
import com.hope.onlinestudy.utils.ApiUtils
import com.hope.onlinestudy.utils.Utils
import kotlinx.android.synthetic.main.view_webview.*
import org.json.JSONObject

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */
class WebViewActivity :
    MVPBaseActivity<WebViewContract.View, WebViewPresenter>(), DownloadListener,
    WebViewContract.View {
    override fun getLayoutView(): Int {
        return R.layout.view_webview
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    @SuppressLint("SetJavaScriptEnabled", "NewApi", "AddJavascriptInterface")
    override fun initData() {
        val tempPath: String? =
            "${ApiUtils.configModel?.sys_base_url}${ApiUtils.configModel?.sys_h5_context}${intent.getStringExtra(
                "url"
            )}"
        val token = "javascript:dispatchJwtToken('${ApiUtils.loginModel?.jwtToken}')"

        val webSettings = wvView.settings
        webSettings.javaScriptEnabled = true//允许使用js
        webSettings.cacheMode = WebSettings.LOAD_DEFAULT
        webSettings.allowUniversalAccessFromFileURLs = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        webSettings.allowFileAccess = true
        //支持屏幕缩放
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        webSettings.displayZoomControls = true
        webSettings.domStorageEnabled = true
        wvView.addJavascriptInterface(this, "android")//添加js监听 这样html就能调用客户端
        wvView.setDownloadListener(this)
        wvView.webChromeClient = object : WebChromeClient() {
            private var mCustomView: View? = null
            private var mCustomViewCallback: CustomViewCallback? = null
            override fun onJsAlert(
                view: WebView,
                url: String,
                message: String,
                result: JsResult
            ): Boolean {
                AlertDialog.Builder(this@WebViewActivity)
                    .setTitle("提示").setMessage(message).show()
                return super.onJsAlert(view, url, message, result)
            }

            @SuppressLint("SourceLockedOrientationActivity")
            override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
                if (mCustomView != null) {
                    callback?.onCustomViewHidden()
                    return
                }
                mCustomView = view
                mFrameLayout.addView(mCustomView)
                mCustomViewCallback = callback
                wvView.visibility = View.GONE
                requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                super.onShowCustomView(view, callback)
            }

            @SuppressLint("SourceLockedOrientationActivity")
            override fun onHideCustomView() {
                wvView.visibility = View.VISIBLE
                if (mCustomView == null) {
                    return
                }
                mCustomView?.visibility = View.GONE
                mFrameLayout.removeView(mCustomView)
                mCustomViewCallback?.onCustomViewHidden()
                mCustomView = null
                requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                super.onHideCustomView()
            }
        }
        wvView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(url)
                return true
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                wvView?.loadUrl(token)
            }


        }

        wvView.loadUrl(tempPath)
    }

    override fun onConfigurationChanged(config: Configuration) {
        super.onConfigurationChanged(config)
        when (config.orientation) {
            Configuration.ORIENTATION_LANDSCAPE -> {
                window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN)
                window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
            }
            Configuration.ORIENTATION_PORTRAIT -> {
                window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
                window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN)
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (wvView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
            wvView.goBack() // goBack()表示返回webView的上一页面
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * JS调用android的方法
     * @param str
     * @return
     */
    @JavascriptInterface
    fun getClient(str: String) {
        Utils.logs("tag", "str = $str")
//        toast(str)
        val jsonModel = JSONObject(str)
        val type = jsonModel.optInt("type")
        val msg = jsonModel.optString("msg")
        if (type == 1) {
            downloadByBrowser(msg)
        }
    }

    @JavascriptInterface
    fun goback() {
        finish()
    }


    public override fun onPause() {
        super.onPause()
        wvView.onPause()
    }

    public override fun onResume() {
        super.onResume()
        wvView.onResume()
    }

    override fun onBackPressed() {
        if (wvView.canGoBack()) {
            wvView.goBack()
            return
        }
        super.onBackPressed()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (null != wvView)
            wvView.destroy()
    }

    override fun onDownloadStart(
        url: String?,
        userAgent: String?,
        contentDisposition: String?,
        mimetype: String?,
        contentLength: Long
    ) {
        downloadByBrowser(url!!)
    }

    private fun downloadByBrowser(url: String) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addCategory(Intent.CATEGORY_BROWSABLE)
        intent.data = Uri.parse(url)
        startActivity(intent)
    }
}